import React from 'react';
import { connect } from 'dva';
import NProgress from 'nprogress';
import './IndexPage.scss';
import { Menu, Icon, Button } from 'antd';
import { Link, Route, Switch } from 'dva/router';
import Video from './view/Video/Video';
import Type from './view/Type/Type';
import Comment from './view/Comment/Comment';
import CommentConfig from './view/Comment/CommentConfig';
import ThemeCommentConfig from './view/ThemeComment/CommentConfig';
import { LocaleProvider } from 'antd';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import Usermanager from './view/Usermanager/Usermanager';
import UserRole from './view/Usermanager/Userrole';
import ThemeComment from './view/ThemeComment/ThemeComment';
import Add from './view/Add/Add';
import Addmongolian from './view/Addmongolian/Add';
import Theme from './view/Theme/Theme';
import UserRight from './view/Usermanager/UserRight';
import NewType from './view/NewType/NewType';
import ThemeDetail from './view/ThemeDetail/ThemeDetail';
import GlobalConfig from './view/GlobalConfig/Config';
import AppGlobalConfig from './view/AppGlobalConfig/AppGlobalConfig';
import AdminGlobalConfig from './view/AdminGlobalConfig/AdminGlobalConfig';
import Regionalism from './view/Regionalism/Regionalism';
import SensitiveWord from './view/SensitiveWord/SensitiveWord'
import Base64 from 'base-64'
import md5 from 'js-md5'
import { UrlConfig, getConfig, waterMarkList } from '../services/fetch';

const SubMenu = Menu.SubMenu;


function authcode(str, key, expiry) {
  var key = key ? key : '';
  var expiry = expiry ? expiry : 0;

  var ckey_length = 4;
  key = md5(key);

  // 密匙a会参与加解密
  var keya = md5(key.substr(0, 16));
  // 密匙b会用来做数据完整性验证
  var keyb = md5(key.substr(16, 16));
  // 密匙c用于变化生成的密文
  // IE下不支持substr第一个参数为负数的情况
  if (ckey_length) {
    var keyc = str.substr(0, ckey_length);

  } else {
    var keyc = '';
  }
  // 参与运算的密匙
  var cryptkey = keya + md5(keya + keyc);

  var strbuf;
  str = str.substr(ckey_length);
  strbuf = Base64.decode(str);
  //string = b.toString();

  var box = new Array(256);
  for (var i = 0; i < 256; i++) {
    box[i] = i;
  }
  var rndkey = new Array();
  // 产生密匙簿
  for (var i = 0; i < 256; i++) {
    rndkey[i] = cryptkey.charCodeAt(i % cryptkey.length);
  }
  // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
  for (var j = i = 0; i < 256; i++) {
    j = (j + box[i] + rndkey[i]) % 256;
    tmp = box[i];
    box[i] = box[j];
    box[j] = tmp;
  }

  // 核心加解密部分
  var s = '';
  let tmp = ''
  //IE下不支持直接通过下标访问字符串的字符，需要先转换为数组
  strbuf = strbuf.split('');
  for (var a = j = i = 0; i < strbuf.length; i++) {
    a = (a + 1) % 256;
    j = (j + box[a]) % 256;
    tmp = box[a];
    box[a] = box[j];
    box[j] = tmp;
    // 从密匙簿得出密匙进行异或，再转成字符
    s += chr(ord(strbuf[i]) ^ (box[(box[a] + box[j]) % 256]));
  }
  if ((s.substr(0, 10) == 0 || s.substr(0, 10) - time() > 0) && s.substr(10, 16) == md5(s.substr(26) + keyb).substr(0, 16)) {
    s = s.substr(26);
  } else {
    s = '';
  }


  return (s);
}

function time() {
  var unixtime_ms = new Date().getTime();
  return parseInt(unixtime_ms / 1000);
}
function chr(s) {
  return String.fromCharCode(s);
}
function ord(s) {
  return s.charCodeAt();
}



@connect(({ video }) => ({
  video,
})) class IndexPage extends React.PureComponent {
  state = {
    collapsed: false,
    permission: []
  }
  componentDidMount() {

    //加载上传插件JS
    let sc = document.createElement('script');
    sc.src = `${UrlConfig}/application/fcpublic/resource/js/fc-upload.js`;
    document.querySelector('body').appendChild(sc);
    //目前暂时取资讯全局配置
    getConfig().then((res) => {
      if (res.data && res.data.code == 200) {
        let { config_json } = res.data.data;
        if(config_json.license&&config_json.license!==''){
          let result = authcode(config_json.license, 'qqknGww6Ncz4PCEV92SMjdndQXBXo0Xb')
        let quanxian = JSON.parse(result)
        this.setState({
          permission: quanxian.list || []
        })
        window.localStorage.setItem('permissionzx', JSON.stringify(quanxian.list))
        if (Array.isArray(quanxian.host) && quanxian.host.indexOf(window.location.host) <= -1) {
          quanxian = []
          window.localStorage.setItem('permissionzx', JSON.stringify(quanxian))
          this.setState({
            permission:[]
          })
        }
        this.props.dispatch({
          type: 'add/configJson', data: config_json
        })
        }else{
          let qx = []
          window.localStorage.setItem('permissionzx', JSON.stringify(qx))
          this.props.dispatch({
            type: 'add/configJson', data: config_json
          })
          this.setState({
            permission:[]
          })
        }
      }
    })

    waterMarkList().then(res => {
      if (res.data.code == 200) {
        let begin = [...res.data.data.data]
        console.log(begin)
        begin.forEach(item => {
          if (item.default == 1) {
            localStorage.setItem('defaultMarkId', item.id)
          }
        })
      }
    })

    let screenWidth = window.screen.width
    if (screenWidth < 1470) {
      this.setState({
        collapsed: true
      })
    }
    let getUrl = window.location.search
    let strr = getUrl.substring(1, getUrl.length)
    let arrStr = strr.split('&')
    let token = ''
    let site_id = ''
    arrStr.map((item, index) => {
      let nameArr = item.split('=')
      if (nameArr[0] === 'token') {
        token = nameArr[1]
      }
      if (nameArr[0] === 'site_id') {
        site_id = nameArr[1]
      }
    })
    localStorage.setItem('token', token);
    localStorage.setItem('site_id', site_id);
    // 获取权限信息
    this.props.dispatch({
      type: 'video/getQuanxian', payload: {
        data: {
          // token: token,
          token: token ? token : 'D3F3C235A8884AC96D5133D810B11CF5',
          site_id: site_id ? site_id : '00000000000000000000000000000000'
        }
      }
    })
  }

  toggleCollapsed = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  }

  render() {

    let quanxian = this.props.video.loginModal.privilege_list ? this.props.video.loginModal.privilege_list : [];
    let hash = window.location.hash
    return (

      <div id='wrap' style={{ display: 'flex', height: '100%' }}>
        <div className='my_Menu' style={this.state.collapsed ? { width: '80px', height: '100%' } :
          { width: '220px', height: '100%' }}>
          {/* <div onClick={this.toggleCollapsed} style={{
            cursor: 'pointer',
            width: '80px', textAlign: 'center', fontSize: '30px', position: 'absolute', top: 0, color: '#fff'
          }}>
            <Icon type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'} />
          </div> */}
          <Menu
            defaultSelectedKeys={[hash]}
            defaultOpenKeys={[]}
            mode="inline"
            inlineCollapsed={this.state.collapsed}
            style={{ height: '100%' }}
          >
            {quanxian.indexOf('privilege/video') > -1 ?
              <Menu.Item key="#/video">
                <Link to='/video'><Icon type="file" />
                  <span>资讯管理</span></Link>
              </Menu.Item>
              : ''}
            {quanxian.indexOf('privilege/type') > -1 ?
              <Menu.Item key="#/type">
                <Link to='/type'><Icon type="layout" />
                  <span>版面管理</span></Link>
              </Menu.Item>
              : ''}
            {quanxian.indexOf('privilege/comment') > -1 || quanxian.indexOf('privilege/commentconfig') > -1 ?
              <SubMenu key="sub3" title={<span><Icon type="solution" /><span>评论管理</span></span>}>
                {quanxian.indexOf('privilege/comment') > -1 ?
                  <Menu.Item key="#/comment"> <Link to='/comment'>评论列表</Link></Menu.Item>
                  : ''}
                {quanxian.indexOf('privilege/commentconfig') > -1 ?
                  <Menu.Item key="#/CommentConfig"> <Link to='/CommentConfig'>评论配置</Link></Menu.Item>
                  : ''}
              </SubMenu>
              : ''}
            {quanxian.indexOf('privilege/theme') > -1 || quanxian.indexOf('privilege/themecomment') > -1 || quanxian.indexOf('privilege/themecommentconfig') > -1 ?
              <SubMenu key="sub2" title={<span><Icon type="profile" /><span>专题管理</span></span>}>
                {quanxian.indexOf('privilege/theme') > -1 ?
                  <Menu.Item key="#/Theme"> <Link to='/Theme'>专题列表</Link></Menu.Item>
                  : ''}
                {quanxian.indexOf('privilege/themecomment') > -1 ?
                  <Menu.Item key="#/ThemeComment"> <Link to='/ThemeComment'>专题评论</Link></Menu.Item>
                  : ''}
                {quanxian.indexOf('privilege/themecommentconfig') > -1 ?
                  <Menu.Item key="#/ThemeCommentConfig"> <Link to='/ThemeCommentConfig'>评论配置</Link></Menu.Item>
                  : ''}

              </SubMenu>
              : ''}
            {quanxian.indexOf('privilege/newtype') > -1 ?
              <Menu.Item key="#/newtype">
                <Link to='/newtype'><Icon type="bars" />
                  <span>分类管理</span></Link>
              </Menu.Item>
              : ''}
            {quanxian.indexOf('privilege/usermanager') > -1 || quanxian.indexOf('privilege/userrole') > -1 ?
              <SubMenu key="sub1" title={<span><Icon type="lock" /><span>权限管理</span></span>}>
                {quanxian.indexOf('privilege/usermanager') > -1 ?
                  <Menu.Item key="#/usermanager"> <Link to='/usermanager'>人员管理</Link></Menu.Item>
                  : ''}
                {quanxian.indexOf('privilege/userrole') > -1 ?
                  <Menu.Item key="#/userrole"> <Link to='/userrole'>角色管理</Link></Menu.Item>
                  : ''}
              </SubMenu>
              : ''}
            {quanxian.indexOf('privilege/globalconfig') > -1 ?
              <SubMenu key="global" title={<span><Icon type="setting" /><span>全局配置</span></span>}>
                <Menu.Item key="#/AppGlobalConfig"> <Link to='/AppGlobalConfig'>APP全局配置</Link></Menu.Item>
                <Menu.Item key="#/AdminGlobalConfig"> <Link to='/AdminGlobalConfig'>后台全局配置</Link></Menu.Item>
                {this.state.permission.indexOf('info_lbs') > -1 && <Menu.Item key="#/Regionalism"> <Link to='/Regionalism'>全国行政区域</Link></Menu.Item>}
              </SubMenu>
              : ''}
            {quanxian.indexOf('privilege/sensitiveword') > -1 ?
              <Menu.Item key="#/sensitiveWord">
                <Link to='/sensitiveWord'><Icon type="file-word" />
                  <span>敏感词管理</span></Link>
              </Menu.Item>
              : ''}
          </Menu>
        </div>
        <div style={{ flex: 1 }}>
          <Switch>
            <Route path="/" exact component={Video} />
            <Route path="/video" exact component={Video} />
            <Route path="/type" exact component={Type} />
            <Route path="/newtype" exact component={NewType} />
            <Route path="/comment" exact component={Comment} />
            <Route path="/CommentConfig" exact component={CommentConfig} />
            <Route path="/ThemeCommentConfig" exact component={ThemeCommentConfig} />
            <Route path="/ThemeComment" exact component={ThemeComment} />
            <Route path="/usermanager" exact component={Usermanager} />
            <Route path="/userrole" exact component={UserRole} />
            <Route path="/userright" exact component={UserRight} />
            <Route path="/theme" exact component={Theme} />{/*专题列表页 */}
            <Route path="/ThemeDetail/:id" exact component={ThemeDetail} /> {/*专题资讯列表页 */}
            <Route path="/globalconfig" exact component={GlobalConfig} />
            <Route path="/AppGlobalConfig" exact component={AppGlobalConfig} />  {/*APP全局配置页 */}
            <Route path="/AdminGlobalConfig" exact component={AdminGlobalConfig} />{/*后端全局配置页 */}
            <Route path="/Regionalism" exact component={Regionalism} />{/*后端全局配置页 */}
            <Route path="/sensitiveWord" exact component={SensitiveWord} />{/*后端全局配置页 */}
          </Switch>
          <div id="fcUpload"></div>
        </div>
      </div>
    );
  }
}

const Routers = () => (
  <LocaleProvider locale={zh_CN}>
    <Switch>
      <Route path="/Add" exact component={Add} />
      <Route path="/Addmongolian" exact component={Addmongolian} />
      <Route path="/AddTheme/:class/:theme_id" exact component={Add} />
      <Route path="/Add/:video_id/:type" exact component={Add} />
      <Route path="/Addmongolian/:video_id/:type" exact component={Addmongolian} />
      <Route component={IndexPage} />
    </Switch>
  </LocaleProvider>
)


export default connect()(Routers);

// const IndexPage= ({ app, loading }) => {

//   let currHref = '';
//   const href = window.location.href;    // 浏览器地址栏中地址
//   if (currHref !== href) {  // currHref 和 href 不一致时说明进行了页面跳转
//       NProgress.start();    // 页面开始加载时调用 start 方法
//       if (!loading.global) {  // loading.global 为 false 时表示加载完毕
//           NProgress.done();  // 页面请求完毕时调用 done 方法
//           currHref = href;   // 将新页面的 href 值赋值给 currHref
//       }
//   }

// }

// export default withRouter(connect(({ app, loading }) => ({ app, loading }))(IndexPage));

